package com.demo.redis.redis;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.nio.charset.StandardCharsets;

@Slf4j
@Service
public class RedisTemplateServcie {

    /**
     * StringRedisTemplate 的默认序列化方式为 StringRedisSerializer
     */
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void pipeLine() {
        int length = 10000;
        final StopWatch stopWatch = new StopWatch();
        stopWatch.start("foreach set");
        for (int i = 0; i < length; i++) {
            stringRedisTemplate.opsForSet().add("key1", String.valueOf(i));
        }
        stopWatch.stop();

        String[] array = new String[length];
        for (int i = 0; i < length; i++) {
            array[i] = String.valueOf(i);
        }

        stopWatch.start("mset");
        stringRedisTemplate.opsForSet().add("key2", array);
        stopWatch.stop();

        stopWatch.start("pipeline set");
        final byte[] key = "key3".getBytes(StandardCharsets.UTF_8);

        stringRedisTemplate.executePipelined((RedisCallback<?>) connection -> {
            for (int i = 0; i < length; i++) {
                connection.sAdd(key, String.valueOf(i).getBytes(StandardCharsets.UTF_8));
            }

            return null;
        });

        stopWatch.stop();
        log.info(stopWatch.prettyPrint());
    }

    public void setValue(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    public String getValue(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 批量添加数据到Set集合
     * @param totalRecords 总记录数
     * @param batchSize 提交批次
     * @param key key
     * @param value 值，在值的末尾添加序号
     */
    public void saddBatch(int totalRecords, int batchSize, String key, String value) {
        int loop = totalRecords / batchSize + 1;
        for (int i = 0; i < loop; i++) {
            String[] values = new String[batchSize];
            for (int j = 0; j < batchSize; j++) {
                values[j] = value + "_" + i + "_" + j;
            }

            totalRecords = totalRecords - batchSize;
            batchSize = totalRecords > batchSize ? batchSize : totalRecords;

            if (values.length > 0) {
                stringRedisTemplate.opsForSet().add(key, values);


            }
        }
    }

    public long sSize(String key) {
        return stringRedisTemplate.opsForSet().size(key);
    }

    public boolean isMember(String key, String value) {
        return stringRedisTemplate.opsForSet().isMember(key, value);
    }
}
